package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.BrandMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.entity.*;
import cn.tedu.csmall.product.pojo.param.BrandAddNewParam;
import cn.tedu.csmall.product.pojo.param.BrandUpdateInfoParam;
import cn.tedu.csmall.product.pojo.vo.BrandListItemVO;
import cn.tedu.csmall.product.pojo.vo.BrandStandardVO;
import cn.tedu.csmall.product.service.IBrandService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.csmall.commons.ex.ServiceException;
import com.example.csmall.commons.pojo.vo.PageData;
import com.example.csmall.commons.util.PageInfoToPageDataConverter;
import com.example.csmall.commons.web.ServiceCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class BrandServiceImpl implements IBrandService {
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private BrandCategoryMapper brandCategoryMapper;
    @Autowired
    private SpuMapper spuMapper;

    @Override
    public void addNew(BrandAddNewParam brandAddNewParam) {
        log.debug("开始处理添加品牌, 参数:{}", brandAddNewParam);
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", brandAddNewParam.getName());
        int countByName = brandMapper.selectCount(queryWrapper);
        log.debug("根据品牌名称统计匹配的品牌数量,结果:{}",countByName);
        if (countByName > 0) {
            String message = "添加品牌失败，品牌名称已经被使用!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
//        将品牌数据写入到数据库中
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandAddNewParam, brand);
        brand.setSales(0);
        brand.setProductCount(0);
        brand.setCommentCount(0);
        brand.setPositiveCommentCount(0);
        brand.setGmtCreate(LocalDateTime.now());
        brand.setGmtModified(LocalDateTime.now());
        log.debug("准备将新的品牌数据写入到数据库，数据：" + brand);
        brandMapper.insert(brand);
        log.debug("将新的品牌数据写入到数据库，完成！");

    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据ID删除品牌】的业务,参数:{}", id);
        // 检查该ID是否有对应的品牌
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = brandMapper.selectCount(queryWrapper);
        if(countById == 0) {
            String message = "删除品牌失败, 该品牌不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        // 检查是否有品牌和分类关联到此品牌，如果存在则抛出异常
        QueryWrapper<BrandCategory> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("brand_id", id);
        int countByBrandId2= brandCategoryMapper.selectCount(queryWrapper2);
        log.debug("根据品牌ID统计匹配的品牌和分类的数量,结果:{}", countByBrandId2);
        if (countByBrandId2 > 0) {
            String message = "删除品牌失败，仍有品牌和分类关联到此品牌！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        // 检查是否有SPU关联到此品牌，如果存在则抛出异常
        QueryWrapper<SPU> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("brand_id", id);
        int countByBrandId4 = spuMapper.selectCount(queryWrapper4);
        log.debug("根据品牌ID统计匹配的SPU数量,结果:{}", countByBrandId4);
        if (countByBrandId4 > 0) {
            String message = "删除品牌失败，仍有SPU关联到此品牌！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        log.debug("开始删除品牌, ID:" + id);
        int rows = brandMapper.deleteById(id);
        if (rows != 1) {
            String message = "修改品牌失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("根据ID删除品牌完成!");
    }
    @Override
    public void updateInfoById(Long id, BrandUpdateInfoParam brandUpdateInfoParam) {
        log.debug("开始处理【修改品牌】的业务,参数:{}，新数据：{}", id, brandUpdateInfoParam);
        // 检查该ID是否有对应的品牌
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = brandMapper.selectCount(queryWrapper);
        if(countById == 0) {
            String message = "修改品牌失败, 该品牌不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查品牌名称是否被其它品牌占用，如果占用则抛出异常
        QueryWrapper<Brand> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("name", brandUpdateInfoParam.getName()).ne("id", id);
        int countByName = brandMapper.selectCount(queryWrapper1);
        log.debug("根据品牌名称统计匹配的品牌数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "修改品牌失败, 该品牌名称已被占用!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }



        // 执行修改品牌
        log.debug("开始修改品牌, ID:" + id);
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandUpdateInfoParam, brand);
        brand.setId(id);
        int rows = brandMapper.updateById(brand);
        if (rows != 1) {
            String message = "修改品牌失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("修改品牌完成!");
    }

    @Override
    public BrandStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询品牌详情】的业务，参数{}", id);
        BrandStandardVO queryResult = brandMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "根据ID查询品牌详情失败，该品牌不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public PageData<BrandListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum, pageSize);
    }

    @Override
    public PageData<BrandListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询相册列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<BrandListItemVO> list = brandMapper.list();;
        PageInfo<BrandListItemVO> pageInfo = new PageInfo<>(list);
        PageData<BrandListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }
}
